<template>
  <div class="mod-config">
    <el-tabs type="border-card">
      <el-tab-pane>
        <span slot="label"><i class="el-icon-date"></i> 商品基本信息</span>
        <el-form :model="dataForm"  ref="dataForm"  label-width="180px">
          <el-form-item label="商品分类" prop="goods.category1Id" >
            <el-select v-model="dataForm.goods.category1Id"   placeholder="一级分类">
              <el-option
                v-for="item in categorys1"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="dataForm.goods.category2Id"  clearable  placeholder="二级分类">
              <el-option
                v-for="item in categorys2"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="dataForm.goods.category3Id" clearable   placeholder="三级分类">
              <el-option
                v-for="item in categorys3"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            模板ID：{{dataForm.goods.typeTemplateId}}
          </el-form-item>
          <el-form-item label="商品名称" style="width: 80%">
            <el-input v-model="dataForm.goods.goodsName" ></el-input>
          </el-form-item>
          <el-form-item label="品牌"  >
            <el-select v-model="dataForm.goods.brandId" clearable  >
              <el-option
                v-for="item in brands"
                :key="item.id"
                :label="item.text"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="副标题" prop="goods.caption" style="width: 80%">
            <el-input v-model="dataForm.goods.caption" ></el-input>
          </el-form-item>
          <el-form-item label="价格" prop="goods.price" style="width: 80%">
            <el-input v-model="dataForm.goods.price" ></el-input>
          </el-form-item>
          <el-form-item label="商品介绍" prop="goodsDesc.introduction"  style="width: 80%">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入商品介绍"
              v-model="dataForm.goodsDesc.introduction">
            </el-input>
          </el-form-item>
          <el-form-item label="包装列表" prop="goodsDesc.introduction" style="width: 80%">
            <el-input v-model="dataForm.goodsDesc.packageList"
                      type="textarea"
                      placeholder="请输入包装列表"
                      :rows="3"></el-input>
          </el-form-item>
          <el-form-item label="售后服务" prop="goodsDesc.introduction" style="width: 80%">
            <el-input v-model="dataForm.goodsDesc.saleService"
                      type="textarea"
                      placeholder="请输入售后服务"
                      :rows="3"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="商品图片">
        <!--1. 上传图片按钮-->
        <el-button type="primary" plain @click="uploadPicHandler">上传图片</el-button>
        <!--2. 图片列表-->
        <el-table
          :data="dataForm.goodsDesc.itemImages"
          style="width: 100%;">
          <el-table-column
            header-align="center"
            align="center"
            label="颜色">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.color }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            header-align="center"
            align="center"
            label="图片">
            <template slot-scope="scope">
              <img :src="scope.row.url" width="80" height="80"/>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="dataForm.goodsDesc.itemImages.splice(scope.$index,1)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="扩展属性">
        <el-table
          :data="dataForm.goodsDesc.customAttributeItems"
          style="width: 100%;">
          <el-table-column
            header-align="center"
            align="center"
            width="300px"
            label="属性名">
            <template slot-scope="scope">
              <span style="margin-left: 10px">{{ scope.row.text }}</span>
            </template>
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            label="属性值">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value"/>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="规格">
        <!--1. 显示规格-->
        <el-table
          :data="specList"
          style="width: 100%;">
          <!--绑定的规格名称-->
          <el-table-column
            header-align="center"
            align="center"
            width="200px">
            <template slot-scope="scope">
              <span style="margin-left: 2px;">{{ scope.row.text }}</span>
            </template>
          </el-table-column>

          <!--绑定的复选框-->
          <el-table-column
            header-align="center"
            prop="options"
            align="left">
            <template slot-scope="scope">
              <el-checkbox-group  size="mini" v-model="optionList[scope.$index]"
                                  @change="getSpecItems">
                <el-checkbox border v-for="option in scope.row.options" :label="option.optionName" :key="option.id" />
              </el-checkbox-group>
            </template>
          </el-table-column>
        </el-table>

        <!--2. 动态显示sku商品列表-->
        <el-table :data="dataForm.items">
          <!--2.1 处理规格及规格选项-->
          <el-table-column :key="key" :label="item['attributeName']" v-for="(item,key) in dataForm.goodsDesc.specificationItems" align="center" >
            <template slot-scope="scope">
              <span >
               {{scope.row.spec[item['attributeName']]}}
              </span>
            </template>
          </el-table-column>
          <!--2.2 处理价格-->
          <el-table-column  label="价格"  align="center" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.price"/>
            </template>
          </el-table-column>
          <!--2.3 处理数量-->
          <el-table-column  label="数量"  align="center" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.num"/>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <div style="margin-top: 20px;">
      <el-button type="success" @click="save">保存</el-button>
      <el-button type="info" plain>返回列表</el-button>
    </div>

    <!--上传图片对话框-->
    <el-dialog
      title="上传商品图片"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible">
      <el-form :model="imageEntity"  label-width="100px">
        {{imageEntity}}
        <el-form-item label="颜色" prop="name">
          <el-input v-model="imageEntity.color" placeholder="颜色"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" prop="firstChar">
          <!--文件上传组件-->
          <!--:http-request="uploadFile" 此代码代表自定义文件上传-->
          <el-upload
            action=""
            class="upload-demo"
            :file-list="fileList"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :http-request="uploadFile"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="addPic">确定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>

  export default {
    data () {
      return {
          dataForm:{goods:{typeTemplateId:''},goodsDesc:{customAttributeItems:[],itemImages:[],specificationItems:[]},items:[]},  // 如果typeTemplateId不设置初始值，就会出现第一次点击3级分类无法出现模板id
          categorys1:[],
          categorys2:[],
          categorys3:[],
          brands:[],
          i:0,
          imageList:[],
          dialogVisible:false,
          imageEntity:{},
          fileList:[],             //上传文件列表
          imageUrl:'',
          specList:[],             //所有的规格及其规格选项集合
        optionList:[],             //规格选项列表
        sName:[],
        header:[],                 //动态显示表头
      }
    },
    watch:{
       //1、 当一级分类发生变化时，自动查询出二级分类
        category1Idnew(newV,oldV) {   //newV：代表我们点击的一级分类的id值
          let id = this.$route.query.id;
          if(newV ){
            this.$http({
              url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
              method: 'get',
            }).then(({data}) => {
              if (data && data.code === 0) {
                if(!id){
                  delete this.dataForm.goods.category2Id;  //删除此变量就不会自动显示了
                }
                  this.categorys2 = data.list;
              }
            })
          }

        },
      //2、 当二级分类发生变化时，自动查询出三级分类
      category2Idnew(newV,oldV) {
        let id = this.$route.query.id;
        if(newV ){
          this.$http({
            url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${newV}`),
            method: 'get',
          }).then(({data}) => {
            if (data && data.code === 0) {
              if(!id){
                delete this.dataForm.goods.category3Id ;  //删除此变量就不会自动显示了
              }
                this.categorys3 = data.list;
            }
          })
        }
      },
      //3、 当三级分类发生变化时，自动查询模板id
      category3Idnew(newV,oldV) {
        if(newV){
          this.$http({
            url: this.$http.adornUrl(`/shop/itemcat/info/${newV}`),
            method: 'get',
          }).then(({data}) => {
            if (data && data.code === 0) {
              //得到模板id
              this.dataForm.goods.typeTemplateId = data.itemCat.typeId;
            }
          })
        }
      },
      //4. 当模板id发生变化时，自动模板中的品牌列表
      typeTemplateIdnew(templateId,oldV){
        let id = this.$route.query.id;
        if(templateId){
          //4.1 查询出此模板下的所有品牌列表
          this.$http({
            url: this.$http.adornUrl(`/shop/typetemplate/info/${templateId}`),
            method: 'get',
          }).then(({data}) => {
            if (data && data.code === 0) {
              // 删除品牌，如果不删除就会出现模板id发生变化时，品牌下拉框中的文本框中还会出现原来的品牌
              if(!id){
                delete this.dataForm.goods.brandId;
                //② 得到自定义扩展属性
                this.dataForm.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems);
              }
              //① 得到品牌列表
              this.brands = JSON.parse(data.typeTemplate.brandIds);
              //③ 得到规格及规格选项列表
              this.findSpecList( JSON.parse(data.typeTemplate.specIds));
            }
          })
        }

      },
        deep:true
    },
    computed: {
      //1. 计算属性category1Id属性值
      category1Idnew() {
        return this.dataForm.goods.category1Id;
      },
      //2. 计算属性category2Id属性值
      category2Idnew() {
        return this.dataForm.goods.category2Id;
      },
      //3. 计算属性category3Id属性值
      category3Idnew() {
        return this.dataForm.goods.category3Id;
      },
      //4. 计算属性typeId属性值
      typeTemplateIdnew(){
        return this.dataForm.goods.typeTemplateId;
      }
    },
    activated () {
      //1. 查询一级分类列表
      this.findByParentId(0);
      //2. 根据商品id查询出相关的所有信息
      this.findById();
    },
    methods: {
      //0.根据商品id查询商品信息
      findById(){
        //0.1 从修改页面传入的商品id
        let id = this.$route.query.id;
        //0.2 从后面根据id查询商品
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/findById/${id}`),
          method: 'post',
        }).then(({data}) => {
          if (data && data.code === 0) {
              this.dataForm = data.goods;
              //① 转换字符串为json对象
            console.log("findById------------------>")
              this.dataForm.goodsDesc.specificationItems=JSON.parse(this.dataForm.goodsDesc.specificationItems)
              this.dataForm.goodsDesc.itemImages=JSON.parse(this.dataForm.goodsDesc.itemImages)
              this.dataForm.goodsDesc.customAttributeItems=JSON.parse(this.dataForm.goodsDesc.customAttributeItems);

              //② 将items里的spec字符串转换为对象
              let skuList = this.dataForm.items;
              for (let i = 0; i < skuList.length; i++) {
                skuList[i].spec = JSON.parse(skuList[i].spec);
              }

              //③ 给optionList赋值，让其自动勾选
              let items = this.dataForm.goodsDesc.specificationItems
              this.optionList=[]
              for(let i = 0;i < items.length;i++){
                this.optionList[i]=items[i].attributeValue;
              }
              console.log("this.optionList===",this.optionList);
              console.log("dataForm-------------->",this.dataForm);

          }
        })
      },
      //1.保存商品
      save(){
        //1.1 从修改页面传入的商品id
        let id = this.$route.query.id;
        let url = "/shop/goods/save";
        if(id){
          url = "/shop/goods/update"
        }
        //1.1 深克隆this.dataForm对象，不然，就会触发触件绑定问题。
        let data = JSON.parse(JSON.stringify(this.dataForm));
        //1.2 将传入到后端的goodsDesc中的内部数组都转为字符串
        data.goodsDesc.specificationItems=JSON.stringify( data.goodsDesc.specificationItems);
        data.goodsDesc.customAttributeItems=JSON.stringify(data.goodsDesc.customAttributeItems)
        data.goodsDesc.itemImages=JSON.stringify(data.goodsDesc.itemImages);
        //1.3 将data.items(sku商品列表)中的spec字段（json对象）
        let items = data.items;
        data.items = items.map(item=>{
          item.spec = JSON.stringify(item.spec);
          return item;
        })
        console.log("dataForm----->",data);
        //1.4 向后端发出保存请求
        this.$http({
          url: this.$http.adornUrl(url),
          method: 'post',
          data
        }).then(({data}) => {
          if (data && data.code === 0) {
            //保存成功后，就恢复默认值
            this.dataForm.goods = {};
            this.dataForm.goodsDesc = {customAttributeItems: [],specificationItems: [],itemImages: []};
            this.dataForm.items = [];
            this.optionList=[];   //选择的规格选项列表
          }
        })
      },
      uploadPicHandler(){
        this.dialogVisible = true;
        this.imageEntity = {}
      },
      //2. 点击规格改变时触发
      getSpecItems(){
        console.log("optionList---->",this.optionList);
        //2.1 根据optionList的值拼装数据
        let specList = [];
        for(let i = 0;i < this.optionList.length;i++){
          specList.push({"attributeName":this.sName[i],"attributeValue":this.optionList[i]});
        }

        //2.2 将组装发好的数据放赋值给this.dataForm.goodsDesc.specificationItems对象
        this.dataForm.goodsDesc.specificationItems = specList;

        //2.3 处理特殊情况：
        // //① 如果this.dataForm.goodsDesc.specificationItems中的某一项的attributeValue的长度为0，就过滤掉
        this.dataForm.goodsDesc.specificationItems=
        this.dataForm.goodsDesc.specificationItems.filter(spec=>{
          return spec.attributeValue.length > 0;
        })
        // //② 如果this.dataForm.goodsDesc.specificationItems中没有数据了，就从 this.dataForm.goodsDesc删除它
        // if(this.dataForm.goodsDesc.specificationItems.length == 0){
        //   delete this.dataForm.goodsDesc.specificationItems;
        // }
        // //2.4 生成items这些sku商品列表
         this.createItemList();
      },


      //3. 当模板id发生变化时，通过规格找到规格选项并返回新的集合
      findSpecList(data){
        this.$http({
          url: this.$http.adornUrl(`/shop/specificationoption/findSpecList`),
          method: 'post',
          data:data
        }).then(({data}) => {
          if (data && data.code === 0) {
             this.specList = data.specList;
             let length = this.specList.length;
             this.header = [];
             for (let i = 0;i < length;i++){
               let specName = this.specList[i].text;
               this.sName[i] = specName;
               console.log("specName-----",specName);
                this.optionList.push([]);
             }
          }
        })
      },

      //4. 上传完成后将图像对象放到this.dataForm.goodsDesc.itemImages这个数组中
      addPic(){
        this.dataForm.goodsDesc.itemImages.push(this.imageEntity);
        this.dialogVisible = false;
      },
      //5. 删除上传文件时触发
      handleRemove(file, fileList) {
        console.log("removeFile:",file);
        this.imageEntity={url:'',color:this.imageEntity.color};
      },
      handlePreview(file) {
        console.log(file);
      },
      //6. 上传文件
      uploadFile(val){
        console.log("uploadFile.....")
        //1. 定义Formdata对象
        let form = new FormData();
        console.log("val:",val)
        form.append("file",val.file);
        //2. 清空上传列表(只能一次上传一个图片)
        this.fileList = [];
        //3. 开始文件上传
        this.$http({
          url:this.$http.adornUrl('/shop/upload'),
          method:'post',
          data:form,
          headers:{'Content-Type': 'multipart/form-data' },
        }).then((data)=>{
          console.log("data:",data)
          if(data && data.data.code === 0 ){
            console.log("url--->",data.data.url);
            //得到上传的图片路径
            //this.imageUrl = data.data.url;
            //将图片路径放到文件列表中，注意，文件格式为：{name:xxx,url:xxx}
            this.fileList.push({name:val.raw,url:data.data.url});
            //将图片地址设置给imageEntity
            this.imageEntity.url = data.data.url;
          }
        })
      },
      //7. 根据父id查询对应列表
      findByParentId(){
          this.$http({
            url: this.$http.adornUrl(`/shop/itemcat/findByParentId/0`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.categorys1 = data.list;
            }
          })
      },
      //8. 生成sku列表
      createItemList(){
        //8.1 设置sku列表的初始值
        this.dataForm.items = [{spec:{},price:0,num:9999,status:'0',isDefault:'0'}]
        //8.2 引用用户选择的规格列表
        let items = this.dataForm.goodsDesc.specificationItems;
        //8.3 遍历这个规格列表，生成新的sku列表
        if(items && items.length > 0){
          items.forEach(item=>{
            this.dataForm.items = this.createCol(this.dataForm.items,item.attributeName,item.attributeValue);
          })
        }

      },
      //9. 创建新列数据
      createCol(items,attributeName,attributeValue){
        //9.1 定义新的数组
        let newList = [];
        //9.2 遍历原始的数组
        items.forEach(oldRow=>{
           attributeValue.forEach(attrValue=>{
             //9.3 根据旧行克隆出新行
             let newRow = JSON.parse(JSON.stringify(oldRow));
             //9.4 向新行中添加数据
             newRow.spec[attributeName] = attrValue;
             //9.5 向新数组中添加新行
             newList.push(newRow);
           })
        })
        //9.5 返回新数组
        return newList;
      }
    }
  }
</script>

<style>
  .bg-purple{
    background-color: rgb(236,236,236);
    padding:10px;
    text-align: center;
    border-bottom: 2px rgb(200,200,200) solid;
  }
  .bg-purple-light{
    padding:10px;
  }

</style>
